/*
 * Copyright 2009 Lukasz Wozniak
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 *
 * http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package pl.lwozniak.blip.message;

import java.io.InputStream;
import java.util.Iterator;

/**
 * Simple class transporting message content to use in creating http requests.
 * 
 * @author Lukasz Wozniak
 * 
 */
public abstract class BlipMessagePart implements Iterable<BlipMessagePart> {

	private BlipMessagePart next;
	private String contentType;
	private String name;
	private SizeHolder sizeHolder;

	public BlipMessagePart(String contentType, String name) {
		super();
		this.contentType = contentType;
		this.name = name;
	}

	public String getContentType() {
		return contentType;
	}

	public String getName() {
		return name;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public void addNext(BlipMessagePart next) {
		if (next != null) {
			if (this.next == null) {
				this.next = next;
				if(sizeHolder==null){
					sizeHolder=new SizeHolder();
				}
				next.sizeHolder=sizeHolder;
				sizeHolder.size++;
			} else {
				this.next.addNext(next);
			}
		} else {
			throw new IllegalArgumentException("next part cannot be null");
		}
	}

	public abstract InputStream getStream();

	public Iterator<BlipMessagePart> iterator() {
		return new BlipMessagePartIterator(this);
	}

	public int getSize() {
		if(sizeHolder==null){
			sizeHolder=new SizeHolder();
		}
		return sizeHolder.size;
	}

	private class BlipMessagePartIterator implements Iterator<BlipMessagePart> {

		private BlipMessagePart current;
		
		public BlipMessagePartIterator(BlipMessagePart current) {
			super();
			this.current = current;
		}

		public boolean hasNext() {
			return current != null;
		}

		public BlipMessagePart next() {
			BlipMessagePart returned = current;
			current = current.next;
			return returned;
		}

		public void remove() {
			// do nothing
		}
	}
	
	private class SizeHolder{
		private int size=1;
	}
}
